const mysql = require("mysql")
const { connect } = require("nodejs-websocket")
const connection = require("nodejs-websocket/Connection")
const { Login } = require("./UserAction")
const DataStruct = require("./DataStruct")
const { RequestCode } = require("./DataStruct")
const DS = require("./DataStruct")
//连接数据库
connectToMysql = () => {
    const connection = mysql.createConnection({
        host: "180.76.139.116",   //服务器ip地址，本地服务器为localhost/127.0.0.1
        user: "aaanuo",   //用户名
        password: "aaanuo",   //密码
        database: "node_server"    //数据库名称
    })
    connection.connect()
    return connection
}

module.exports = {
    Login: (data, connect) => {
        //连接数据库，每次新的要求都要调用此函数来连接数据库
        let connection = connectToMysql()
        connection.query('select id,name from db_user1 where account="' + data.account + '" and password="' + data.password + '"', (error, result) => {
            if (error) throw error
            console.log('----------QueryResult------------')
            console.log(result)
            let data = new Object()

            if (result.length !== 0) {
                data.code = 200
                data.msg = "登录成功"
                data.data = result[0]
                connect.id = result[0].id
                connect.name = result[0].name
                connect.isReady = false
            } else {
                data.code = 403
                data.msg = "账号或密码错误"
                data.data = null
            }
            //打包数据
            let msg = DS.packData(DS.RequestCode.USER, DS.UserAction.LOGIN, data)
            //发送消息
            connect.sendText(msg)
            //每次查询完毕后关闭mysql连接
            connection.end((error) => {
                if (error) throw error
                console.log('signUp:0数据库关闭连接')
            })

            // //创建一个对象
            // let res=new Object()
            // //设置requestCode
            // res.requestCode=DataStruct.RequestCode.USER
            // res.acctionCode=DataStruct.RequestCode.Login
            // res.data=result
            // let str_res = JSON.stringify(res)
            // connect.sendText(str_res)
        })
    },
    //注册
    signUp: (data, connect) => {
        if (data.name.length > 0 && data.name.length <= 6 && data.account.length >= 6 && data.password.length >= 6) {
            //连接数据库
            let connection = connectToMysql()
            //利用sql语句查询账号是否已经注册
            connection.query('select * from db_user1 where account="' + data.account + '"', (error, result) => {
                if (error) throw error
                //该用户未被注册
                if (result.length === 0) {
                    console.log('账号未被注册')
                    //利用sql语句将用户信息插入表格中
                    connection.query(`insert into db_user1(name, account, password)values('${data.name}','${data.account}','${data.password}')`, (error, result) => {
                        let data = new Object()
                        if (error) throw error
                        if (result !== 0) {
                            data.code = 200
                            data.msg = '注册成功'
                            data.data = true
                        } else {
                            data.code = 200
                            data.msg = '注册失败'
                            data.data = null
                        }
                        //打包数据
                        let msg = DS.packData(DS.RequestCode.USER, DS.UserAction.SIGNUP, data)
                        //发送消息
                        connect.sendText(msg)
                        //每次查询完毕后关闭mysql连接
                        connection.end((error) => {
                            if (error) throw error
                            console.log('signUp:1数据库关闭连接')
                        })
                    })
                }
                else {
                    // console.log('账号已注册')
                    let data = new Object()
                    data.code = 200
                    data.msg = "账号已存在"
                    data.data = null
                    //打包数据
                    let msg = DS.packData(DS.RequestCode.USER, DS.UserAction.SIGNUP, data)
                    //发送消息
                    connect.sendText(msg)
                    // connect.sendText("格式不符合")
                    //每次查询完毕后关闭mysql连接
                    connection.end((error) => {
                        if (error) throw error
                        console.log('signUp:2数据库关闭连接')
                    })
                }
            })
        } else {
            let data = new Object()
            data.code = 200
            data.msg = "账号或密码或姓名格式错误"
            data.data = null
            //打包数据
            let msg = DS.packData(DS.RequestCode.USER, DS.UserAction.SIGNUP, data)
            //发送消息
            connect.sendText(msg)
        }
    },

    get_info:(data,connect)=>
    {
        
        let get_info_data = new Object();
        let connection = connectToMysql();
        connection.query('select name,time from db_user1',(error,result)=>{
            if(error) throw error;
            if(result.length!==0)
            {
                // console.log("11111",result);
                for(let i =0;i<result.length;i++)
                {
                    for(let j = i+1;j<result.length;j++)
                    {
                        if (result[i].time>result[j].time) {
                            let val = result[i]
                            result[i] = result[j]
                            result[j] = val;
                        }
                    }
                }
                console.log(result);
            }
            get_info_data.info = result;
            //get_info_data= 20;
            let msg =  DataStruct.packData(DataStruct.RequestCode.USER,DataStruct.UserAction.GET_INFO,get_info_data);
            connect.sendText(msg);
            connection.end((error)=>{
                if(error) throw error;
                console.log("login: 数据库连接关闭");
            })

        })
    },
    updata_info:(data,connect)=>{
        let get_info_data = new Object();
        let connection = connectToMysql();
        connection.query('UPDATE db_user1 SET time='+data.time+' where id="'+connect.id+'"',(error,result)=>{
            if(error) throw error;
            if(result.length!==0)
            {
                get_info_data.id = connect.id;
                get_info_data.data = null;
                get_info_data.code = 200;
                get_info_data.msg = "存入数据库成功";
            }
            let msg =  DataStruct.packData(DataStruct.RequestCode.USER,DataStruct.UserAction.UPDATE_INFO,get_info_data);
            connect.sendText(msg);
            connection.end((error)=>{
                if(error) throw error;
                console.log("login: 数据库连接关闭");
            })
        })  
    }
}

